/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controladorUploadImagen;

import modeloUploadImagen.FileUpload;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author CEBALLOS
 */
public class FileUploadServer extends HttpServlet {

    private int i = -1;
    public ArrayList<String> datos = new ArrayList<>();

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();


        HttpSession session = request.getSession();


        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {

            ServletFileUpload upload = new ServletFileUpload();

            try {
                FileItemIterator itr = upload.getItemIterator(request);

                while (itr.hasNext()) {

                    FileItemStream item = itr.next();
                    //String name = item.getFieldName();

                    //String fileName = item.getName();

                    if (item.isFormField()) {
                        InputStream stream = item.openStream();
                        //do field specific procces
                        String fieldName = item.getFieldName();
                        //do file upload specific procces
                        InputStream Archivo = item.openStream();
                        i = i + 1;
                        System.out.println("---------" + i);

                        byte[] b = new byte[Archivo.available()];
                        Archivo.read(b);

                        String value = new String(b);
                        System.out.println(b + "--Valor String de la imagen---");
                        System.out.println(fieldName + ":" + value + "");
                        datos.add(i, value);
                        System.out.println(datos);
                        //response.getWriter().println(fieldName + ":" + value + "<br/>");

                    } else {

                        String cedula = datos.get(0);
                        String nombres = datos.get(1);

                        String ruta = getServletContext().getRealPath("");


                        if (isNumeric(cedula)) {
                            System.out.println(cedula + " es un numero");
                            //call method to upload file
                            if (FileUpload.ProcesarArchivo(ruta, item)) {
                                FileUpload FL = new FileUpload();
                                FL.ProcesarArchivosql(ruta, item, Integer.parseInt(cedula), nombres);
                                datos.clear();
                                i = -1;
                                //response.sendRedirect("imagenget/faces/");
                                // response.getWriter().println("window.location.href='?backurl='+window.location.href;");
                                response.getWriter().println("Registro correcto");

                                response.setContentType("text/html");
                                out.println("<script type=\"text/javascript\">");
                                out.println("window.onload = function myFunction()");
                                out.println("{");
                                out.println("alert('Correcto Usuario Agregado')");
                                out.println("window.location.href='/imagenget/faces/index.xhtml';");
                                out.println("}");
                                out.println("</script>");

                                //response.sendRedirect("/imagenget/faces/index.xhtml");


                            } else {

                                datos.clear();
                                i = -1;
                                
                                
                               // String valor = request.getParameter("nombres");
                                
                                //session.setAttribute("error", "No se envio el parametro de busqueda!!!" + valor); // request.getRequestDispatcher("/imagenget/faces/index.xhtml").forward(request, response);
                                response.getWriter().println("archivo no subido, faltan campos");
                               // String url = response.encodeRedirectURL("/imagenget/faces/index.xhtml");
                               // response.sendRedirect(url);
                            }
                        } else {
                            System.out.println(cedula + "el campo cedula debe ser un numero");

                            response.setContentType("text/html");
                            out.println("<script type=\"text/javascript\">");
                            out.println("window.onload = function myFunction()");
                            out.println("{");
                            out.println("alert('Error! El campo cedula debe ser un numero , intentelo nuevamente')");
                            out.println("window.location.href='/imagenget/faces/index.xhtml';");
                            out.println("}");
                            out.println("</script>");

                            response.getWriter().println("el campo cedula debe ser un numero");
                            response.getWriter().println("archivo no subido");
                            datos.clear();
                            i = -1;
                        }
                    }

                }
            } finally {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(FileUploadServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(FileUploadServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private boolean isNumeric(String cedula) {

        try {
            Integer.parseInt(cedula);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }


    }
}
